package com.myideas.service.impl;

import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;

import com.myideas.model.User;
import com.myideas.service.SecurityManager;


/**
 * Implementation of LookupManager interface to talk to the persistence layer.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class SecurityManagerImpl /*extends UniversalManagerImpl*/ implements SecurityManager {
//    private UserDao dao;
//
//    /**
//     * Method that allows setting the DAO to talk to the data store with.
//     * @param dao the dao implementation
//     */
//    public void setUserDao(UserDao dao) {
//        this.dao = dao;
//    }

    /**
     * {@inheritDoc}
     */
    public User getUserLoggedIn() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();

        if (auth == null)
        	throw new RuntimeException("Authentication context not present (null)");

        User currentUser;
        if (auth.getPrincipal() instanceof UserDetails) {
        	currentUser = (User) auth.getPrincipal();
        } else if (auth.getDetails() instanceof UserDetails) {
        	currentUser = (User) auth.getDetails();
        } else {
        	throw new AccessDeniedException("User not properly authenticated.");
        }
        return currentUser;
    }

}
